<!--  -->
<template>
  <div class="size-full">
    <div class="flex h-8 justify-center space-x-2">
      <ScreenButton :active="activeTab == 0" @click="switchTab(0)">项目统计</ScreenButton>
      <ScreenButton :active="activeTab == 1" @click="switchTab(1)">机构统计</ScreenButton>
    </div>
    <div style="height: calc(100% - 32px)" class="w-full" ref="ChartRight3"></div>
    <DialogBox
      :title="`中介超市Top5热门${activeTab == 0 ? '项目' : '机构'}类别清单`"
      :show="showDialog"
      @close="showDialog = false"
      @opened="initDetail"
    >
      <DivideSelector
        :list="tableTab"
        @change="changeTableTab"
        :gridNum="tableTab.length"
        :activeIndex="detailActiveLabel"
      ></DivideSelector>
      <el-table
        :data="tableData"
        stripe
        max-height="492px"
        style="width: 100%"
        class="table mt-[22px]"
        height="455px"
      >
        <el-table-column v-if="activeTab === 0" prop="itemname" label="项目名称" />
        <el-table-column v-if="activeTab === 0" prop="createdate" label="成交时间" />
        <el-table-column v-if="activeTab === 1" prop="agencyname" label="中介机构名称" />
        <el-table-column v-if="activeTab === 1" prop="legal" label="法人代表" />
        <el-table-column v-if="activeTab === 1" prop="creditcode" label="统一社会信用代码" />
        <el-table-column v-if="activeTab === 1" prop="grade" label="等级" />
      </el-table>
      <div class="mt-3 justify-end flex">
        <el-pagination
          @change="initTableApi"
          background
          layout="prev, pager, next"
          :total="totals"
          size="small"
          style="--el-pagination-button-bg-color: transparent; --el-disabled-bg-color: transparent"
        />
      </div>
    </DialogBox>
  </div>
</template>

<script setup lang="ts">
import { requestApi } from '@/api'
import ScreenButton from '@/components/botton/ScreenButton.vue'
import DialogBox from '@/components/box/DialogBox.vue'
import DivideSelector from '@/components/left/Inner/components/DivideSelector.vue'
import { useCounterStore } from '@/stores/counter'
import type { eChartDataType, HotTaskTop5DetailItem, HotTop5DetailItem } from '@/types/baseTypes'
import { defaultTooltipStyle, useEcharts } from '@/util/e-chart'
import type { EChartsOption } from 'echarts'
import * as echarts from 'echarts'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'

const store = useCounterStore()
const { speechSumNumber } = storeToRefs(store)
const showDialog = ref(false)

const activeTab = ref(0)

const ChartRight3 = ref<HTMLElement>()

let mainChart: useEcharts

const getProjectSum = (): Promise<[string[], number[]]> => {
  return new Promise((resolve) => {
    requestApi.GetWjzjHotTop5().then((res) => {
      let labels: string[] = []
      let values: number[] = []
      let tableTabData: { label: string; value: string }[] = []
      res.forEach((item) => {
        labels.push(item.name)
        values.push(item.value)
        tableTabData.push({
          label: item.name,
          value: item.taskguid
        })
      })
      tableTab.value = tableTabData
      resolve([labels, values])
    })
  })
}

const getInstitutionSum = (): Promise<[string[], number[]]> => {
  return new Promise((resolve) => {
    requestApi.GetHotTaskTop5().then((res) => {
      let labels: string[] = []
      let values: number[] = []
      let tableTabData: { label: string; value: string }[] = []
      res.forEach((item) => {
        labels.push(item.name)
        values.push(item.value)
        tableTabData.push({
          label: item.name,
          value: item.taskguid
        })
      })
      tableTab.value = tableTabData
      resolve([labels, values])
    })
  })
}

const initMainChart = async () => {
  const Data = getMainOption(...(await getProjectSum()))
  mainChart = new useEcharts(
    ChartRight3.value!,
    Data,
    (data) => {
      detailActiveLabel.value = tableTab.value.find((e) => e.label == data.name)?.value
      initTable()
    },
    true
  )
}

const detailActiveLabel = ref()
const getMainOption = (xAxis: string[], data: number[]): EChartsOption => {
  let data1 = data
  let data1val: eChartDataType[] = xAxis.map((e) => {
    return { value: Math.max(...data) * 1.5, name: e }
  })
  // 生成带索引的数据数组并计算排名
  let rankings = data1
    .map((value, index) => ({ value, index })) // 创建对象数组，包含值和原始索引
    .sort((a, b) => b.value - a.value) // 按值降序排序
  // 计算排名，处理相同值的情况
  let rankByIndex = new Array(data1.length)
  let currentRank = 0
  let lastValue: any = null

  rankings.forEach((item, i) => {
    if (item.value !== lastValue) {
      currentRank = i + 1 // 排名从1开始
    }
    rankByIndex[item.index] = currentRank // 为原始索引分配排名
    lastValue = item.value // 更新上一个值
  })
  // 定义颜色映射
  let labelColors = ['#ff9330', '#E8BC5D', '#7BE897', '#00FFF4', '#48E3DC']
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: (params: any) => {
        const pm = params[3]
        return `<div>${pm.axisValue}</div><div class="flex items-center"><div class="chart-symbol" style="background-color:${labelColors[rankByIndex[pm.dataIndex] - 1]}"></div>${pm.value}</div>`
      },
      ...defaultTooltipStyle
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 60,
      top: 40
    },
    xAxis: {
      data: xAxis,
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        interval: 0,
        color: '#fff',
        fontSize: 14,
        width: 100,
        overflow: 'break',
        align: 'center',
        lineHeight: 20,
        margin: 20 //刻度标签与轴线之间的距离。
      }
    },
    yAxis: {
      show: false
    },
    series: [
      {
        name: '外部底部圆',
        type: 'pictorialBar',
        symbolSize: [30, 15],
        symbolOffset: [0, 10],
        z: 12,
        itemStyle: {
          opacity: 1,
          color: '#29528F'
        },
        data: [1, 1, 1, 1, 1]
      },
      {
        name: '外部部头部圆',
        type: 'pictorialBar',
        symbolSize: [30, 15],
        symbolOffset: [0, -10],
        z: 1,
        symbolPosition: 'end',
        itemStyle: {
          opacity: 1,
          color: function () {
            return new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: '#0D2640' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#305DA9' // 100% 处的颜色
                }
              ],
              false
            )
          },
          borderColor: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#091C2F' },
            { offset: 1, color: '#207AF1' }
          ]),
          borderWidth: 10 // 边框宽度
        },
        data: data1val
      },

      {
        name: '内部底部圆',
        type: 'pictorialBar',
        symbolSize: [30, 15],
        symbolOffset: [0, 5],
        z: 12,
        itemStyle: {
          opacity: 1,
          color: '#4D88D6'
        },
        data: [1, 1, 1, 1, 1]
      },

      {
        name: '内部头部圆',
        type: 'pictorialBar',
        symbolSize: [30, 15],
        symbolOffset: [0, -10],
        z: 12,
        itemStyle: {
          opacity: 1,
          color: function () {
            return new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0.51,
                  color: '#457CD4' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#2856B6' // 100% 处的颜色
                }
              ],
              false
            )
          }
        },
        symbolPosition: 'end',
        data: data1
      },

      {
        name: '外部透明圆柱',
        type: 'bar',
        barWidth: 30,
        z: 0,
        itemStyle: {
          color: function () {
            return new echarts.graphic.LinearGradient(
              1,
              0,
              0,
              0,
              [
                {
                  offset: 0,
                  color: '#207AF1' // 0% 处的颜色（左边）
                },
                {
                  offset: 0.2,
                  color: '#207AF100' // 30% 处开始为深色
                },
                {
                  offset: 0.8,
                  color: '#207AF100' // 70% 处结束深色
                },
                {
                  offset: 1,
                  color: '#207AF1' // 100% 处的颜色（右边）
                }
              ],
              false
            )
          }
        },
        label: {
          fontFamily: 'D-DIN-PRO-500-Medium',
          show: true, // 显示标签
          position: 'top', // 标签显示在柱体顶部
          offset: [0, -10], // 向上偏移 10 像素
          formatter: function (params: any) {
            return data1[params.dataIndex] // 返回data1的数据
          },
          color: 'inherit',
          fontSize: 20
        },
        data: data1val.map((item, index) => {
          item.label = {
            color: labelColors[rankByIndex[index] - 1]
          }
          return item
        })
      },
      {
        name: '内部圆柱',
        type: 'bar',
        barGap: '-100%',
        barWidth: 30,
        itemStyle: {
          color: function () {
            return new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: '#79D0F8' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#4D88D6' // 100% 处的颜色
                }
              ],
              false
            )
          }
        },
        label: {
          fontFamily: 'D-DIN-PRO-500-Medium',
          show: true, // 显示标签
          position: 'top', // 标签在柱体顶部
          formatter: function (params: any) {
            return `NO.${rankByIndex[params.dataIndex]}` // 显示排名，索引+1
          },
          color: '#fff', // 标签文字颜色
          fontSize: 16, // 标签字体大小
          offset: [0, -10] // 向上偏移标签
        },
        data: data1
      }
    ] as any
  }
}
onMounted(() => {
  initMainChart()
  requestApi.GetWjzjHotTop5().then((res) => {
    res.forEach((res) => {
      if (res.name == '造价咨询') {
        speechSumNumber.value.right3.consult = res.value
      }
      if (res.name == '政府采购代理') {
        speechSumNumber.value.right3.business = res.value
      }
    })
  })

  requestApi.GetHotTaskTop5().then((res) => {
    res.forEach((res) => {
      if (res.name == '房产经纪') {
        speechSumNumber.value.right3.building = res.value
      }
      if (res.name == '货运代理') {
        speechSumNumber.value.right3.order = res.value
      }
    })
  })
})

const switchTab = async (idx: number) => {
  activeTab.value = idx
  const getData = idx == 0 ? await getProjectSum() : await getInstitutionSum()
  const Data = getMainOption(...getData)
  mainChart.setOption(Data)
}

const activeTableTab = ref<string>('')
const tableTab = ref<{ label: string; value: string }[]>([])

const initTable = () => {
  showDialog.value = true
}

const changeTableTab = (idx: string | number) => {
  activeTableTab.value = `${idx}`
  initDetail()
}

const tableData = ref<HotTop5DetailItem[] | HotTaskTop5DetailItem[]>([])
const totals = ref(100)
const page = ref(0)
const initTableApi = (e: number) => {
  console.log(e)
  page.value = e - 1
  initDetail()
}

//弹窗内逻辑
const initDetail = () => {
  if (activeTab.value == 0) {
    requestApi
      .GetWjzjHotTop5Detail({
        taskguid: activeTableTab.value,
        first: page.value,
        pageSize: 10
      })
      .then((res) => {
        totals.value = res.datacount
        tableData.value = res.datalist
      })
  } else {
    requestApi
      .GetHotTaskTop5Detail({
        taskguid: activeTableTab.value,
        first: page.value,
        pageSize: 10
      })
      .then((res) => {
        totals.value = res.datacount
        tableData.value = res.datalist
      })
  }
}
</script>
<style scoped lang="less">
.table {
  --el-table-tr-bg-color: #19aeef20;
  --el-table-header-bg-color: #0a577b;
  --el-fill-color-lighter: #0000;
  --el-table-header-text-color: #fff;
}
</style>
